package com.lianzhihui.romeex.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.text.TextUtils;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;

import com.chaychan.library.BottomBarItem;
import com.chaychan.library.BottomBarLayout;
import com.google.zxing.client.android.Intents;
import com.lianzhihui.romeex.R;
import com.lianzhihui.romeex.bean.UserInfoBean;
import com.lianzhihui.romeex.config.AppConstants;
import com.lianzhihui.romeex.mvp.presenter.MainPresnterImp;
import com.lianzhihui.romeex.mvp.view.MainActivityView;
import com.lianzhihui.romeex.ui.base.BaseActivity;
import com.lianzhihui.romeex.ui.mianfragment.EcologicalFragment;
import com.lianzhihui.romeex.ui.mianfragment.MeFragment;
import com.lianzhihui.romeex.ui.mianfragment.OrePoolFragment;
import com.lianzhihui.romeex.ui.mianfragment.TradeFragment;
import com.lianzhihui.romeex.ui.mianfragment.WalletFragment;
import com.lianzhihui.romeex.ui.qrcode.ScanActivity;
import com.lianzhihui.romeex.utils.LogUtil;
import com.lianzhihui.romeex.utils.QrUtils.QRUtils;
import com.lianzhihui.romeex.utils.StatusBarUtil;
import com.lianzhihui.romeex.utils.UserUtils;
import com.lianzhihui.romeex.widget.MyViewPager;
import com.lianzhihui.romeex.widget.dialog.InputInvCodeDialog;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class MainActivity extends BaseActivity implements BottomBarLayout.OnItemSelectedListener, MainActivityView {

    @BindView(R.id.mViewPager)
    MyViewPager mViewPager;
    @BindView(R.id.bottom_bar)
    BottomBarLayout bottomBar;
    @BindView(R.id.bottom_content)
    CardView bottomContent;
    @BindView(R.id.main_wallet_oc_lin_main)
    LinearLayout mainWalletOcLinMain;
    private ArrayList<Fragment> fragmentList;
    public static MainActivity instance;
    private MainPresnterImp mainPresnterImp;
    private InputInvCodeDialog inputInvCodeDialog;
    private boolean goScanActivityFlag = false;
    private boolean isAttach = false;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    public static void reLogin(Activity activity) {
        if (instance != null) {
            instance.finish();
        }
        Intent intent = new Intent(activity, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        activity.startActivity(intent);
    }

    @Override
    public boolean setFitSystemWindowFlag() {
        return false;
    }

    @Override
    protected void initView() {
        instance = this;
        hideBar();
        StatusBarUtil.setTransparentForImageViewInFragment(this, null);
        checkPermission();

        fragmentList = new ArrayList<>();
        fragmentList.add(OrePoolFragment.newInstance());
        fragmentList.add(TradeFragment.newInstance());
        fragmentList.add(WalletFragment.newInstance());
        fragmentList.add(EcologicalFragment.newInstance());
        fragmentList.add(MeFragment.newInstance());

        FragmentManager fragmentManager = getSupportFragmentManager();
        MyFragmentAdapter adapter = new MyFragmentAdapter(fragmentManager, fragmentList);
        mViewPager.setScrollable(false);
        mViewPager.setOffscreenPageLimit(5);
        mViewPager.setAdapter(adapter);
        bottomBar.setOnItemSelectedListener(this);
        bottomBar.setCurrentItem(2);
        mainPresnterImp = new MainPresnterImp(this, this);
    }


    @Override
    protected void initData() {
        mViewPager.setCurrentItem(0, false);
        bottomBar.setCurrentItem(0);
    }

    @Override
    public void onItemSelected(BottomBarItem bottomBarItem, int i, int i1) {
        if (i1 == 3) {
            StatusBarUtil.setStatusBarTextColor(this, false);
        } else {
            StatusBarUtil.setStatusBarTextColor(this, true);
        }
        mViewPager.setCurrentItem(i1, false);
    }


    @Override
    public void setFailure() {
        dismissLoading();
        showDialog();
    }


    @Override
    public void responseUserSuccess(UserInfoBean data) {
        if (data.isOpenStatus()) {
            //已经绑定
            UserUtils.setCurrentOpenStatus(data.isOpenStatus());
        } else {
            //未绑定
            if (inputInvCodeDialog == null) {
                showDialog();
            }
        }
    }

    @Override
    public void responseBindParentSuccess() {
        UserUtils.setCurrentOpenStatus(true);
        toast(getResources().getString(R.string.text_inv_binded_success));
        dismissLoading();
    }


    public static class MyFragmentAdapter extends FragmentPagerAdapter {
        private List<Fragment> fragments;

        public MyFragmentAdapter(FragmentManager fm, List<Fragment> fragments) {
            super(fm);
            this.fragments = fragments;
        }

        @Override
        public Fragment getItem(int i) {
            return fragments.get(i);
        }


        @Override
        public int getCount() {
            return fragments.size();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!UserUtils.getCurrentOpenStatus()) {
            if (goScanActivityFlag) {
                return;
            }
            mainPresnterImp.requestUserInfo();
        }
    }

    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        LogUtil.debug("xxxxxx", "onAttachedToWindow-------------------");
        isAttach = true;
    }

    private void showDialog() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                LogUtil.debug("xxxxx", "showDialog--------------->>>>>>>>");
                if (isAttach && !MainActivity.this.isDestroyed() && inputInvCodeDialog == null) {
                    inputInvCodeDialog = new InputInvCodeDialog(MainActivity.this);
                    inputInvCodeDialog.setCallback(new InputInvCodeDialog.Callback() {
                        @Override
                        public void confirm(String s) {
                            showLoading("");
                            inputInvCodeDialog.dismiss();
                            inputInvCodeDialog = null;
                            mainPresnterImp.requestBindParent(s);
                        }

                        @Override
                        public void scan() {
                            goScanActivity();
                        }
                    });
                    inputInvCodeDialog.setCancelable(false);
                    inputInvCodeDialog.fullWidth();
                    inputInvCodeDialog.show();
                }
            }
        }, 1000);

    }


    private void goScanActivity() {
        //扫描
        goScanActivityFlag = true;
        Intent intent = new Intent(this, ScanActivity.class);
        startActivityForResult(intent, AppConstants.MAIN_REQUEST_CODE_SCAN);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 扫描二维码/条码回传
        if (requestCode == AppConstants.MAIN_REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
            if (data != null) {
                //返回的文本内容
                String content = data.getStringExtra(Intents.Scan.RESULT);
                if (TextUtils.isEmpty(content)) {
                    toast("无效二维码");
                    return;
                }
                if (QRUtils.scanType(content) != 4) {
                    toast(getString(R.string.text_is_not_inv_code));
                    return;
                }
                switch (QRUtils.scanType(content)) {
                    case 4:
                        //邀请
                        String inv_code = QRUtils.getContentString(content, 4);
                        inputInvCodeDialog.setInvCode(inv_code);
                        break;
                    default:
                        break;
                }
            }
        }
    }


}